const { Transform } = require("stream");
const Excel = require('exceljs');
const fs = require("fs-extra");
const path = require("path");
const _ = require("lodash");
const utils = require('../../utils');

module.exports = function (file, sheetName = 'Sheet1') {
  const stream = new Transform({ objectMode: true });
  fs.ensureDirSync(path.dirname(file));
  const wb = new Excel.Workbook();
  const ws = wb.addWorksheet(sheetName);
  
  let hasTitle = false;
  let keys;

  stream._transform = function (chunk, encoding, callback) {
    stream.push(chunk);
    utils.debug('excelWriter [chunk]:', chunk);
    if (!hasTitle && _.isPlainObject(chunk)) {
      hasTitle = true;
      keys = _.keys(chunk);
      ws.columns = _.map(keys, o=>({ header: o }));
    }
    ws.addRow(_.values(chunk));
    callback();
  };

  stream.on('finish', async function () {
    await wb.xlsx.writeFile(file);
    utils.debug('excelWriter [finish]');
  });

  return stream;
};